#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/CI/lib -I/data/Software/mydan/CI/private/lib
use strict;
use warnings;

use Logs;
use FindBin qw( $RealBin );
use MIME::Base64;
use File::Basename;

$| ++;

=head1 SYNOPSIS

    db => $mysql,
    logs => 日志对象

    #index uuid temp path addr ticketid tags

=cut

return sub
{
    my %param = @_;

    my ( $db,$logs, $index, $uuid, $temp, $path, $addr, $ticketid, $tags  ) 
        = @param{qw(db logs index uuid temp path addr ticketid tags )};

    $logs = Logs->new( 'code.build.dump.rely.svn' ) unless $logs;

    my ( $username, $pass );

    if( $ticketid )
    {
        my $x = eval{ $db->query( "select ticket from ticket where id='$ticketid' and type='UsernamePassword'" )};  
        $logs->die( "get data from ticket fail:$@" ) if $@;
        ( $username, $pass ) = split /_:separator:_/, $x->[0][0] if @$x;
    }

    #TODO
    #my $ctrl = $pass ? "svn --username '$username'  --password '" . decode_base64( $pass ) . "'" : 'svn';
    my $ctrl = $pass ? "svn --username '$username'  --password '" . $pass . "'" : 'svn';

    my $temppath = "$RealBin/../logs/$temp/$uuid/rely/$index";
    if( -d $temppath )
    {
        $logs->die( "clean old temppath fail:$!" ) if system "rm -rf '$temppath'";
    }
    $logs->die( "mkdir temppath fail:$!" ) if system "mkdir -p '$temppath'";


    if( $tags )
    {
        $logs->die( "tags format error" ) unless $tags =~ /^[a-zA-Z0-9\.\-_]+$/;
        $logs->die( "clone error: $!" ) 
            if system "cd '$temppath' && rm -rf data '$tags' info && $ctrl checkout '$addr/tags/$tags' && mkdir -p info && mv '$tags/.svn' info/ && mv '$tags' data && echo '$tags' > info/version";
    }
    else
    {
        $logs->die( "clone error: $!" ) 
            if system "cd '$temppath' && rm -rf data trunk info && $ctrl checkout '$addr/trunk' && mkdir -p info && mv 'trunk/.svn' info/ && mv 'trunk' data && echo release > info/version";
    }


    if( $path )
    {
        $logs->die( "path format error" ) unless $path =~ /^[a-zA-Z0-9\.\-\_\/]+$/ && $path =~ /[a-zA-Z0-9]+/;
        my $subpath = "$RealBin/../logs/$temp/$uuid/data/$path";
        my $pathbase = dirname $subpath;

        unless( -d $pathbase )
        {
            $logs->die( "mkdir subpath fail:$!" ) if system( "mkdir -p '$pathbase'" );
        }

        if( -e $subpath )
        {
            $logs->die( "remove subpath fail:$!" ) if system( "rm -rf '$subpath'" );
        }

        $logs->die( "mv subpath fail:$!" ) if system "mv '$temppath/data' '$subpath'";
    }
}
